package top.ninwoo.utils.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.ninwoo.utils.service.DockerService;
import top.ninwoo.utils.service.OVSService;
import top.ninwoo.utils.service.OvsDockerService;
import top.ninwoo.utils.util.LinuxCtlUtils;
import top.ninwoo.utils.util.OvsDockerUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class OvsDockerServiceImpl implements OvsDockerService {
    // 在这里维护docker 和 ovs port之间的关联
    private ConcurrentHashMap<String, Set<String>> dockerPorts = new ConcurrentHashMap<>();

    @Autowired
    OvsDockerUtils ovsDockerUtils;

    @Autowired
    OVSService ovsService;

    @Autowired
    DockerService dockerService;

    @Override
    public String addPort(String bridgeName, String devName, String containerId, String ip) {
        // 做一些校验
        if(!ovsService.isBridge(bridgeName)) {
            throw new RuntimeException("网桥[" + bridgeName + "]不存在！");
        }
        if(!dockerService.hasRunningContainer(containerId)) {
            throw new RuntimeException("容器[" + containerId + "]不存在");
        }

        String portId = ovsDockerUtils.addPort(bridgeName, devName, containerId, ip);
        if (!dockerPorts.containsKey(containerId)) {
            dockerPorts.put(containerId, new HashSet<String>());
        }

        dockerPorts.get(containerId).add(bridgeName + ":" + portId);

        return portId;
    }

    /**
     * 删除docker的虚拟网卡
     * @param bridgeName
     * @param devName
     * @param containerId
     * @return
     */
    @Override
    public boolean delPort(String bridgeName, String devName, String containerId) {
        if(!ovsService.isBridge(bridgeName)) {
            throw new RuntimeException("网桥[" + bridgeName + "]不存在！");
        }
        if(!dockerService.hasRunningContainer(containerId)) {
            throw new RuntimeException("容器[" + containerId + "]不存在");
        }
        String res = ovsDockerUtils.delPort(bridgeName, devName, containerId);
        if("".equals(res)) {
            return true;
        }
        return false;
    }

    /**
     * 获取docker的ovs网络端口
     * @param containerId
     * @return
     */
    @Override
    public Set<String> getContainerPorts(String containerId) {
        if(!dockerPorts.containsKey(containerId)) {
            return new HashSet<>();
        }
        return dockerPorts.get(containerId);
    }

    @Override
    public void deleteContainerPorts(String containerId) {
        // 获取docker端口
        Set<String> containerPorts = getContainerPorts(containerId);
        containerPorts.forEach( p -> {
            String br = p.split(":")[0];
            String port = p.split(":")[1];
            ovsService.delBridgePort(br, port);
        });
    }
}
